package com.phalanxim.dao.impl;

import com.phalanxim.dao.CustomerDao;
import com.phalanxim.service.Customer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Repository("customerDao")
public class CustomerDaoImpl implements CustomerDao
{
  @Autowired
  private SessionFactory sessionFactory;
  // Customer
  @Transactional(readOnly = true)
  public List<Customer> getCustomerList()
  {
    Session session = sessionFactory.openSession(); // not part of a transaction, so we need to open a session manually
    List<Customer> customers = session.createQuery("from Customer customer").list();
    session.close();
    return customers;
  }

  @Transactional(readOnly = true)
  public Customer findCustomer(Long id)
  {
    Session session = sessionFactory.openSession();
    Customer customer = (Customer)session.createCriteria(Customer.class).add(Restrictions.eq("id", id)).uniqueResult();
    session.close();
    return customer;
  }

  @Transactional
  public Customer saveCustomer(Customer customer)
  {
    Session session = sessionFactory.getCurrentSession();
    session.save(customer);
    return customer;
  }

  @Transactional
  public Customer updateCustomer(Customer customer)
  {
    Session session = sessionFactory.getCurrentSession();
    session.update(customer);
    return customer;
  }

  @Transactional
  public Customer removeCustomer(Customer customer)
  {
    Session session = sessionFactory.getCurrentSession();
    session.delete(customer);
    return customer;
  }
}
